package vn.com.shoppie.object;

import vn.com.shoppie.util.SUtilXml;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

public class AsynBluetooth extends AsyncTask<String, Integer, Boolean> {
	int duration = 0;
	static int time = 0;
	BluetoothAdapter mBluetoothAdapter;
	boolean firstEnable = false;
	Context context;

	public AsynBluetooth(Context context, int duration) {
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		this.duration = duration;
		if (mBluetoothAdapter != null)
			firstEnable = mBluetoothAdapter.isEnabled();
		this.context = context;
	}

	@SuppressWarnings("static-access")
	@Override
	protected Boolean doInBackground(String... arg0) {
		if (mBluetoothAdapter == null)
			return false;
		if (time > 0)
			return false;
		publishProgress(time);
		while (time < duration) {
			if (!mBluetoothAdapter.isEnabled()) {
				mBluetoothAdapter.enable();
			}
			else if (!mBluetoothAdapter.isDiscovering()) {
				mBluetoothAdapter.startDiscovery();
			} else {
				time++;
			}
			try {
				Thread.currentThread().sleep(1000);
			} catch (InterruptedException e) {
				time = 0;
				return false;
			}
			this.publishProgress(time);
		}
		time = 0;
		return true;
	}

	@Override
	protected void onProgressUpdate(Integer[] values) {
		int time = values[0];
		if (time > 0 && time < duration) {

		} else if (time == 0) {

		}
		//Log.e("discovering", values[0] + "second" + mBluetoothAdapter.isDiscovering());
	};

	protected void onPostExecute(Boolean result) {
		if (SUtilXml.getInstance().registerAccount(context) > -1) {
			Toast.makeText(context, "Get User Info successful!", Toast.LENGTH_SHORT).show();
		}
		if(mBluetoothAdapter==null) return;
		if (mBluetoothAdapter.isDiscovering()) {
			mBluetoothAdapter.cancelDiscovery();
		}
		if (!firstEnable)
			mBluetoothAdapter.disable();
	};

}
